package ilearning.demo.utils;

import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.NacosConfigService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;

import java.util.Map;
import java.util.Objects;

/**
 * @author Wang Xu
 * @date 2023/11/8
 */
public class NacosConfigUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(NacosConfigUtil.class);

    private static ConfigService configService;

    public static void setConfigService(ConfigService configService) {
        NacosConfigUtil.configService = configService;
    }

    public static String getByDataId(String dataId) {
        try {
            return configService.getConfig(dataId, "group-test1", 100);
        } catch (NacosException e) {
            LOGGER.error("nacos data query error, msg is :", e);
        }
        return null;
    }
    public static <T> T getValue(String dataId, String key, Class<T> clazz) {
        if (Objects.isNull(key) || key.length() == 0) {
            return null;
        }
        String content = getByDataId(dataId);
        Yaml yaml = new Yaml();
        Map<String,Object> map = yaml.load(content);
        String[] split = key.split("\\.");
        Object v = null;
        Map<String,Object> tmp = map;
        for (int i = 0; i < split.length; i++) {
            String s = split[i];
            v = tmp.get(s);
            if (i == split.length - 1) {
                break;
            }
            tmp = Objects.isNull(tmp.get(s)) ? null : (Map<String,Object>)tmp.get(s);
            if(Objects.isNull(tmp)){
                v = null;
                break;
            }
        }
        return clazz.cast(v);
    }
}